<template>
  <view class="uni-container">
    <uni-forms ref="form" :model="formData" validate-trigger="submit" err-show-type="toast">
		<uni-forms-item name="url" label="壁纸" required>
			<image class="item image" @click="imageClick" :src="imageHandler(formData.url)" mode="aspectFit"></image>
        </uni-forms-item>
		<uni-forms-item name="desc" label="描述" required>
          <uni-easyinput autoHeight :trim="true"  type="textarea"  placeholder="请描述一下壁纸，仅用于搜索时检索，不会展示" v-model="formData.desc"></uni-easyinput>
        </uni-forms-item>
        <uni-forms-item name="direction" label="方向" required>
          <uni-data-checkbox selectedColor="#32DBBA" selectedTextColor="#32DBBA" v-model="formData.direction" :localdata="formOptions.direction_localdata"></uni-data-checkbox>
        </uni-forms-item>

      <view class="uni-button-group">
        <button type="primary"  class="uni-button subbtn" @click="submit">提交修改</button>
		<button type="warn" class="btn-delete" @click="handleDelete">删除</button>
      </view>
    </uni-forms>
  </view>
</template>

<script>
  import { validator } from '../../js_sdk/validator/wallpaper-userShare.js';
	import { imageHandler } from '@/utils/common.js'

  const db = uniCloud.database();
  const dbCollectionName = 'wallpaper-userShare';

  function getValidator(fields) {
    let result = {}
    for (let key in validator) {
      if (fields.indexOf(key) > -1) {
        result[key] = validator[key]
      }
    }
    return result
  }

  

  export default {
    data() {
      let formData = {
        "title": "",
        "desc": "",
        "url": "",
        "direction": null,
        "count": 0,
        "status": 0
      }
      return {
	    oldData:formData,
        formData,
        formOptions: {
          "direction_localdata": [
            {
              "value": 0,
              "text": '横屏'
            },
            {
              "value": 1,
              "text": '竖屏'
            }
          ]
        },
        rules: {
          ...getValidator(Object.keys(formData))
        }
      }
    },
    onLoad(e) {
      if (e.id) {
        const id = e.id
        this.formDataId = id
        this.getDetail(id)
		
      }
    },
    onReady() {
      this.$refs.form.setRules(this.rules)
    },
    methods: {
		handleDelete(){
			// 真删
			uni.showModal({
				title: '提示',
				content: '确认要删除吗？',
				success:async (e) => {
					if (e.confirm) {
						try {
							const res = await db.collection(dbCollectionName).doc(this.formDataId).remove()
							uniCloud.callFunction({
								name: 'my-deleteFiles',
								data: {
									fileList: [this.formData.url] // 替换为你要删除的文件 ID
								},
								success: (res) => {
									// console.log('删除结果:', res.result);
									console.log('删除成功');
									uni.showToast({
										title: '删除成功'
									})
									this.getOpenerEventChannel().emit('refreshData')
									setTimeout(() => uni.navigateBack(), 500)
								},
								fail: (error) => {
									uni.showToast({
										title: '删除失败'
									})
									// console.error('删除失败:', error);
									console.log('删除失败');
								}
							});
						} catch (error) {
							uni.showToast({
								title: '删除失败'
							})
						}
						
					}
				}
			})
			/* 状态改为删除
			uni.showModal({
				title: '提示',
				content:'确认要删除吗？',
				success:(e) => {
					if(e.confirm){
						db.collection(dbCollectionName).doc(this.formDataId).update({
							status: 4
						}).then((res) => {
						  uni.showToast({
						    icon: 'none',
						    title: '删除成功'
						  })
						  this.getOpenerEventChannel().emit('refreshData')
						  setTimeout(() => uni.navigateBack(), 500)
						}).catch((err) => {
						  uni.showModal({
						    content: err.message || '请求服务失败',
						    showCancel: false
						  })
						})
					}
				}
			})*/
		},
		imageClick(){
			// uni.showToast({
			// 	title: '壁纸无法修改',
			// 	icon: 'none'
			// })
			uni.previewImage({
				urls: [imageHandler(this.formData.url)]
			})

		},
      imageHandler,
      /**
       * 验证表单并提交
       */
      submit() {
		  uni.showModal({
		  	title:'提示',
			content: '提交修改后需要重新审核，确认提交？',
			success:(e) => {
				if(e.confirm){
					// 对比对象				
					uni.showLoading({
					  mask: true
					})
					this.$refs.form.validate().then((res) => {
						if(JSON.stringify(this.oldData) === JSON.stringify(this.formData)){
							uni.showToast({
								title: '内容没有变化',
								icon: 'none'
							})
							return
						}
						res.status = 0
					  return this.submitForm(res)
					}).catch(() => {
					}).finally(() => {
					  uni.hideLoading()
					})
				}
			}
		  })
      },

      /**
       * 提交表单
       */
      submitForm(value) {
        // 使用 clientDB 提交数据
        return db.collection(dbCollectionName).doc(this.formDataId).update(value).then((res) => {
          uni.showToast({
            icon: 'none',
            title: '提交成功'
          })
          this.getOpenerEventChannel().emit('refreshData')
          setTimeout(() => uni.navigateBack(), 500)
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        })
      },

      /**
       * 获取表单数据
       * @param {Object} id
       */
      getDetail(id) {
        uni.showLoading({
          mask: true
        })
        db.collection(dbCollectionName).doc(id).field("title,desc,url,direction,count,status").get().then((res) => {
          const data = res.result.data[0]
          if (data) {
            this.formData = data
            this.oldData = Object.assign({}, this.formData);
          }
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        }).finally(() => {
          uni.hideLoading()
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .uni-container {
    padding: 15px;
  }

  :deep(){
		// 提交按钮
		.uni-button {
			background-color: $theme-bg-color2!important;
			margin-bottom: 20rpx;
		}
  		.image{
  			background-color: transparent!important;
  		}
		/* #ifndef MP-WEIXIN */
		.image > *{
			background-position: left center!important;
		}
		/* #endif */
		/* #ifdef MP-WEIXIN */
		.image > img{
			background-position: left center!important;
		}
		/* #endif */
		
  		.uni-section-header__decoration {
  			background-color: $theme-bg-color2!important;
  		}
		.is-focused {
			border-color: $theme-bg-color2!important;
		}
		.uni-data-checklist,.checklist-group{
			height: 100%;
		}
		.uni-forms-item__content{
			overflow: hidden;
		}
		
  	}
  	.item{
  		padding-left: 30rpx;
  		display: block;
  		font-size: 36rpx;
		
  	}
  	.item.image{
  		padding-left: 0rpx;
  		display: block;
  		max-width: 100%;
		max-height: 400rpx;
  	}
  .container {
    padding: 10px;
  }
  
  .btns {
    margin-top: 10px;
    /* #ifndef APP-NVUE */
    display: flex;
    /* #endif */
    flex-direction: row;
  }
  
  .btns button {
    flex: 1;
  }
</style>
